<template>
  <el-dialog :visible.sync="$store.state.searchVisible" title="搜索" width="950px" @update:visible="handleClose"
    custom-class="search-dialog" center>
    <div class="search-input-wrapper" :class="{ loading }">
      <i class="fas fa-search search-icon"></i>
      <input ref="searchInput" v-model="params.keyword" type="text" class="search-input" placeholder="输入关键词搜索文章..."
        @input="handleInputChange" @keyup.enter="handleSearch" />
      <div v-show="params.keyword" class="clear-btn" @click="clearSearch">
        <i class="fas fa-times"></i>
      </div>
      <span class="enter-tip" v-show="!params.keyword">
        <i class="fas fa-keyboard"></i>
        输入关键词, 按回车搜索
      </span>
    </div>

    <!-- 搜索建议 -->
    <div v-if="showSuggestions && searchSuggestions.length > 0" class="search-suggestions">
      <div v-for="(suggestion, index) in searchSuggestions" :key="index" class="suggestion-item"
        @click="useSuggestion(suggestion)">
        <i class="fas fa-search-plus"></i>
        <span v-html="highlightKeyword(suggestion)"></span>
      </div>
    </div>

    <div class="hot-searches" v-show="searchResults.length === 0 && !hasSearched">
      <!-- 搜索历史记录 -->
      <div class="search-history-section" v-show="searchHistory.length > 0">
        <div class="history-header">
          <h4>
            <i class="fas fa-clock"></i>
            搜索历史
          </h4>
          <button class="clear-history-btn" @click="clearSearchHistory">
            <i class="fas fa-trash-alt"></i>
            清空
          </button>
        </div>
        <div class="history-list">
          <div class="history-item" v-for="(item, index) in displayedHistory" :key="index"
            @click="useHistoryKeyword(item)">
            <span class="history-icon">
              <i class="fas fa-search"></i>
            </span>
            <span class="history-keyword">{{ item }}</span>
            <span class="history-delete" @click.stop="removeFromHistory(item)">
              <i class="fas fa-times-circle"></i>
            </span>
          </div>

          <!-- 展开/收起按钮 -->
          <div v-if="searchHistory.length > 3" class="history-expand" @click="toggleHistoryExpand">
            <span v-if="!historyExpanded">
              <i class="fas fa-angle-down"></i> 展开更多 ({{ searchHistory.length - 3 }})
            </span>
            <span v-else>
              <i class="fas fa-angle-up"></i> 收起
            </span>
          </div>
        </div>
      </div>

      <!-- 热门搜索关键词 -->
      <div class="hot-keywords-section" v-show="hotKeywords.length > 0">
        <div class="hot-keywords-header">
          <h4>
            <i class="fas fa-fire"></i>
            热门搜索
          </h4>
        </div>
        <div class="hot-keywords-list">
          <div class="hot-keyword-item" v-for="(keyword, index) in displayedHotKeywords" :key="index"
            @click="useHistoryKeyword(keyword)">
            <span class="hot-keyword-rank" :class="{ 'top-rank': index < 3, 'normal-rank': index >= 3 }">{{ index + 1
              }}</span>
            <span class="hot-keyword-text">{{ keyword }}</span>
          </div>
        </div>

        <!-- 展开/收起热门搜索按钮 -->
        <div v-if="hotKeywords.length > 6" class="hot-keywords-expand" @click="toggleHotKeywordsExpand">
          <span v-if="!hotKeywordsExpanded">
            <i class="fas fa-angle-down"></i> 展开更多 ({{ hotKeywords.length - 6 }})
          </span>
          <span v-else>
            <i class="fas fa-angle-up"></i> 收起
          </span>
        </div>
      </div>

      <h4>
        <i class="fas fa-hashtag"></i>
        标签搜索
      </h4>
      <div class="hot-tags">
        <router-link v-for="(tag, index) in tags" :key="tag.id" :to="`/tags?tagId=${tag.id}&tagName=${tag.name}`"
          :class="['hot-tag', 'tag-color-' + (index % 9)]">
          {{ tag.name }}
        </router-link>
      </div>
    </div>

    <div v-show="searchResults.length > 0" class="search-results" v-loading="loading">
      <div v-for="item in searchResults" :key="item.id" class="search-result-item" @click="handleResultClick(item)">
        <div class="result-header">
          <h3 v-html="highlightKeyword(item.title)"></h3>
          <span class="result-date">{{ formatDate(item.createTime) }}</span>
        </div>
        <p class="result-summary" v-html="highlightKeyword(item.summary)"></p>
        <div class="result-footer">
          <span class="result-category">
            <i class="fas fa-folder"></i>
            {{ item.categoryName }}
          </span>
          <span class="result-views">
            <i class="fas fa-eye"></i>
            {{ item.quantity }} 阅读
          </span>
        </div>
      </div>

      <div class="pagination-box">
        <el-pagination v-show="total > 0" background @current-change="handlePageChange" :current-page="params.pageNum"
          :page-size="params.pageSize" layout="prev, pager, next" :total="total">
        </el-pagination>
      </div>
    </div>

    <el-empty v-show="searchResults.length === 0 && params.keyword.trim()" description="没有找到相关文章..." />
    <el-empty v-show="searchResults.length === 0 && !params.keyword.trim()" description="输入关键词搜索文章.." />
  </el-dialog>
</template>

<script>
import { getArticlesApi, searchArticlesApi, getHotSearchKeywordsApi, getSearchSuggestionsApi, fuzzySearchArticlesApi } from '@/api/article'
import { getTagsApi } from '@/api/tags'
import DOMPurify from 'dompurify'

export default {
  name: 'SearchDialog',

  data() {
    return {
      searchResults: [],
      loading: false,
      searchTimeout: null,
      suggestionsTimeout: null,
      tags: [],
      params: {
        keyword: '',
        pageNum: 1,
        pageSize: 10
      },
      hasSearched: false,
      total: 0,
      // 搜索历史记录
      searchHistory: [],
      // 搜索历史是否展开
      historyExpanded: false,
      // 热门搜索关键词
      hotKeywords: [],
      // 最大历史记录数
      maxHistoryItems: 10,
      // 热门搜索是否展开
      hotKeywordsExpanded: false,
      // 最大展示热门搜索数
      maxHotKeywordsDisplay: 10,
      // 标签颜色配置
      tagColors: [
        { bg: 'linear-gradient(135deg, #ff9a9e 0%, #fad0c4 100%)', color: '#333' },
        { bg: 'linear-gradient(135deg, #a1c4fd 0%, #c2e9fb 100%)', color: '#333' },
        { bg: 'linear-gradient(135deg, #fbc2eb 0%, #a6c1ee 100%)', color: '#333' },
        { bg: 'linear-gradient(135deg, #84fab0 0%, #8fd3f4 100%)', color: '#333' },
        { bg: 'linear-gradient(135deg, #fccb90 0%, #d57eeb 100%)', color: '#333' },
        { bg: 'linear-gradient(135deg, #e0c3fc 0%, #8ec5fc 100%)', color: '#333' },
        { bg: 'linear-gradient(135deg, #f6d365 0%, #fda085 100%)', color: '#333' },
        { bg: 'linear-gradient(135deg, #43e97b 0%, #38f9d7 100%)', color: '#333' },
        { bg: 'linear-gradient(135deg, #fa709a 0%, #fee140 100%)', color: '#333' },
      ],
      // 搜索建议
      searchSuggestions: [],
      showSuggestions: false,
      // 模糊搜索相关设置 (默认禁用，使用精准搜索API)
      useFuzzySearch: false,
      fuzzySearchDistance: 2,
      // 是否正在获取建议
      loadingSuggestions: false
    }
  },
  computed: {
    // 控制显示的历史记录条目
    displayedHistory() {
      if (this.historyExpanded || this.searchHistory.length <= 3) {
        return this.searchHistory;
      } else {
        return this.searchHistory.slice(0, 3);
      }
    },
    // 控制显示的热门搜索条目
    displayedHotKeywords() {
      if (this.hotKeywordsExpanded || this.hotKeywords.length <= 6) {
        // 限制最多显示10个
        return this.hotKeywords.slice(0, this.maxHotKeywordsDisplay);
      } else {
        return this.hotKeywords.slice(0, 6);
      }
    }
  },
  watch: {
    '$store.state.searchVisible': {
      handler(newVal) {
        if (newVal) {
          this.fetchTags();
          this.loadSearchHistory();
          this.fetchHotKeywords();
          // 初始状态为收起
          this.historyExpanded = false;
          this.hotKeywordsExpanded = false;
          this.$nextTick(() => {
            if (this.$refs.searchInput) {
              this.$refs.searchInput.focus();
            }
          });
        }
      }
    }
  },
  methods: {
    /**
     * 获取标签列表
     */
    async fetchTags() {
      try {
        const res = await getTagsApi();
        this.tags = res.data;
        // 为每个标签预生成颜色，避免反复计算
        this.tags = this.tags.map(tag => {
          const randomColor = this.tagColors[Math.floor(Math.random() * this.tagColors.length)];
          return {
            ...tag,
            style: {
              background: randomColor.bg,
              color: randomColor.color
            }
          }
        });
      } catch (error) {
        console.error('获取标签失败:', error);
      }
    },

    /**
     * 从本地存储加载搜索历史
     */
    loadSearchHistory() {
      try {
        const history = localStorage.getItem('searchHistory');
        this.searchHistory = history ? JSON.parse(history) : [];
      } catch (error) {
        console.error('加载搜索历史失败:', error);
        this.searchHistory = [];
      }
    },

    /**
     * 获取热门搜索关键词
     */
    fetchHotKeywords() {
      try {
        getHotSearchKeywordsApi(this.maxHotKeywordsDisplay).then(res => {
          if (res.data) {
            this.hotKeywords = res.data;
          }
        });
      } catch (error) {
        console.error('获取热门搜索关键词失败:', error);
        this.hotKeywords = [];
      }
    },

    /**
     * 保存搜索历史到本地存储
     */
    saveSearchHistory() {
      try {
        localStorage.setItem('searchHistory', JSON.stringify(this.searchHistory));
      } catch (error) {
        console.error('保存搜索历史失败:', error);
      }
    },

    /**
     * 添加关键词到搜索历史
     */
    addToSearchHistory(keyword) {
      if (!keyword || keyword.trim() === '') return;

      // 移除已存在的相同关键词
      this.searchHistory = this.searchHistory.filter(item => item !== keyword);

      // 添加到头部
      this.searchHistory.unshift(keyword);

      // 限制最多保存10条
      if (this.searchHistory.length > this.maxHistoryItems) {
        this.searchHistory = this.searchHistory.slice(0, this.maxHistoryItems);
      }

      // 保存到本地存储
      this.saveSearchHistory();
    },

    /**
     * 从历史记录中删除关键词
     */
    removeFromHistory(keyword) {
      this.searchHistory = this.searchHistory.filter(item => item !== keyword);
      this.saveSearchHistory();
    },

    /**
     * 清空搜索历史
     */
    clearSearchHistory() {
      this.$confirm('确定要清空所有搜索历史记录吗?', '确认操作', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        this.searchHistory = [];
        this.saveSearchHistory();
        this.$message({
          type: 'success',
          message: '搜索历史已清空'
        });
      }).catch(() => {
        // 用户取消操作，不做任何处理
      });
    },

    /**
     * 使用历史记录中的关键词进行搜索
     */
    useHistoryKeyword(keyword) {
      this.params.keyword = keyword;
      this.handleSearch();
    },

    /**
     * 展开/收起历史记录
     */
    toggleHistoryExpand() {
      this.historyExpanded = !this.historyExpanded;
    },

    /**
     * 展开/收起热门搜索
     */
    toggleHotKeywordsExpand() {
      this.hotKeywordsExpanded = !this.hotKeywordsExpanded;
    },

    /**
     * 为标签生成随机样式
     */
    getRandomTagStyle() {
      const randomColor = this.tagColors[Math.floor(Math.random() * this.tagColors.length)];
      return {
        background: randomColor.bg,
        color: randomColor.color
      };
    },

    /**
     * 获取搜索建议
     */
    fetchSearchSuggestions(keyword) {
      if (!keyword || keyword.trim().length < 2) {
        this.searchSuggestions = [];
        this.showSuggestions = false;
        return;
      }

      this.loadingSuggestions = true;

      // 清除之前的定时器
      if (this.suggestionsTimeout) {
        clearTimeout(this.suggestionsTimeout);
      }

      // 设置延迟，避免频繁请求
      this.suggestionsTimeout = setTimeout(() => {
        getSearchSuggestionsApi(keyword.trim())
          .then(res => {
            if (res.data && res.data.length > 0) {
              this.searchSuggestions = res.data;
              // 只有在用户没有正在尝试搜索时才显示建议
              if (!this.loading) {
                this.showSuggestions = true;
              }
            } else {
              this.searchSuggestions = [];
              this.showSuggestions = false;
            }
          })
          .catch(error => {
            console.error('获取搜索建议失败:', error);
            this.searchSuggestions = [];
            this.showSuggestions = false;
          })
          .finally(() => {
            this.loadingSuggestions = false;
          });
      }, 200); // 减少到200毫秒，提高响应速度
    },

    /**
     * 使用搜索建议进行搜索
     */
    useSuggestion(suggestion) {
      this.params.keyword = suggestion;
      this.showSuggestions = false;
      // 点击建议后立即执行搜索
      this.handleSearch();
    },

    /**
     * 处理搜索选项变更
     */
    handleSearchOptionChange() {
      if (this.params.keyword.trim()) {
        this.handleSearch();
      }
    },

    /**
     * 处理输入变化
     */
    handleInputChange() {
      if (this.searchTimeout) {
        clearTimeout(this.searchTimeout);
      }

      const trimmedKeyword = this.params.keyword.trim();

      // 只获取搜索建议，不触发搜索
      this.fetchSearchSuggestions(trimmedKeyword);

      // 如果清空了关键词，也清空搜索结果
      if (!trimmedKeyword && this.hasSearched) {
        this.clearSearchResults();
      }
    },

    /**
     * 清空搜索结果
     */
    clearSearchResults() {
      this.searchResults = [];
      this.hasSearched = false;
    },

    /**
     * 处理分页
     */
    handlePageChange(page) {
      this.params.pageNum = page
      this.handleSearch()
    },
    /**
     * 将Markdown转换为纯文本
     */
    markdownToPlainText(markdown) {
      if (!markdown) return ''

      // 预处理: 处理可能的HTML编码
      let text = markdown
        .replace(/&lt;/g, '<')
        .replace(/&gt;/g, '>')
        .replace(/&amp;/g, '&')
        .replace(/&quot;/g, '"')
        .replace(/&#39;/g, "'")

      // 清除整个代码块（包括语法标识和内容）
      text = text.replace(/```[\s\S]*?```/g, ' ')
      text = text.replace(/~~~[\s\S]*?~~~/g, ' ') // 另一种代码块标记
      text = text.replace(/<pre[\s\S]*?<\/pre>/gi, ' ') // HTML pre标签
      text = text.replace(/<code[\s\S]*?<\/code>/gi, ' ') // HTML code标签

      // 清除行内代码，保留内容
      text = text.replace(/`([^`]+)`/g, '$1')

      // 清除图片，包括各种格式
      text = text.replace(/!\[.*?\]\(.*?\)/g, '')
      text = text.replace(/!\[.*?\]\[.*?\]/g, '')
      text = text.replace(/!\[\]\(.*?\)/g, '') // 无文本图片
      text = text.replace(/<img[^>]*>/g, '')

      // 清除链接，保留链接文本
      text = text.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '$1') // [text](url)
      text = text.replace(/\[([^\]]+)\]\[([^\]]+)\]/g, '$1') // [text][ref]
      text = text.replace(/\[([^\]]+)\]\[\]/g, '$1') // [text][] 隐式引用
      text = text.replace(/<a[^>]*>(.*?)<\/a>/g, '$1') // HTML链接
      text = text.replace(/\[\]\(.*?\)/g, '') // 无文本链接
      text = text.replace(/\[.*?\]:\s*.*?$/gm, '') // 链接定义

      // 清除所有HTML注释和其他标签
      text = text.replace(/<!--[\s\S]*?-->/g, '')
      text = text.replace(/<([^>]+)>/g, '') // 所有其他HTML标签

      // 清除标题符号
      text = text.replace(/^#{1,6}\s+/gm, '')
      text = text.replace(/\n[=-]{2,}$/gm, '') // 清除 === 和 --- 形式的标题
      text = text.replace(/^(.+)\n[=]{2,}$/gm, '$1') // 一级标题
      text = text.replace(/^(.+)\n[-]{2,}$/gm, '$1') // 二级标题

      // 清除各种文本装饰（可能嵌套）
      // 先处理嵌套和组合格式
      text = text.replace(/(\*\*\*|___)(.*?)\1/g, '$2') // 加粗斜体
      text = text.replace(/(\*\*|__)(.*?)\1/g, '$2') // 加粗
      text = text.replace(/(\*|_)(.*?)\1/g, '$2') // 斜体
      text = text.replace(/~~(.*?)~~/g, '$1') // 删除线
      text = text.replace(/==(.*?)==/g, '$1') // 高亮文本
      text = text.replace(/\^\^(.*?)\^\^/g, '$1') // 上标
      text = text.replace(/~(.*?)~/g, '$1') // 下标
      text = text.replace(/\+\+(.*?)\+\+/g, '$1') // 下划线

      // 重复一次，以防有多层嵌套
      text = text.replace(/(\*\*\*|___)(.*?)\1/g, '$2')
      text = text.replace(/(\*\*|__)(.*?)\1/g, '$2')
      text = text.replace(/(\*|_)(.*?)\1/g, '$2')
      text = text.replace(/~~(.*?)~~/g, '$1')
      text = text.replace(/==(.*?)==/g, '$1')

      // 可能残留的单独标记
      text = text.replace(/[\*_~=\+\^]/g, ' ')

      // 清除列表符号
      text = text.replace(/^[\*\-+•●○■□◆◇▪▫]\s+/gm, '') // 各种列表标记
      text = text.replace(/^\d+\.\s+/gm, '') // 数字列表
      text = text.replace(/^\s*[\*\-+•●○■□◆◇]\s+/gm, '') // 缩进列表
      text = text.replace(/^\s*\d+\.\s+/gm, '') // 缩进数字列表
      text = text.replace(/^(\s*)\[\s?\]\s+/gm, '$1') // 未选中复选框
      text = text.replace(/^(\s*)\[x\]\s+/gmi, '$1') // 已选中复选框

      // 清除引用符号（多层引用和嵌套）
      text = text.replace(/^>\s+/gm, '')
      text = text.replace(/^>+\s*/gm, '')

      // 清除表格格式
      text = text.replace(/\|.*\|/g, (match) => {
        return match.replace(/\|/g, ' ').replace(/[-:]+/g, ' ');
      })
      // 彻底移除表格分隔符行
      text = text.replace(/^\s*[-:]+[-|\s:]*[-:]+\s*$/gm, '')

      // 清除水平线
      text = text.replace(/^[\*\-=_]{3,}$/gm, '')

      // 清除脚注
      text = text.replace(/\[\^.+?\](?:\: .*?$)?/gm, '')
      text = text.replace(/^\[\^.+?\]:.+$/gm, '') // 脚注定义

      // 清除数学公式和LaTeX
      text = text.replace(/\$\$(.*?)\$\$/g, '')
      text = text.replace(/\$(.*?)\$/g, '')
      text = text.replace(/\\begin\{.*?\}[\s\S]*?\\end\{.*?\}/g, '')
      text = text.replace(/\\[a-zA-Z]+\{.*?\}/g, '')

      // 清除角色标记和提及
      text = text.replace(/@[\w-]+/g, '')
      text = text.replace(/#[\w-]+/g, '') // 标签

      // 清除URL和邮箱
      text = text.replace(/https?:\/\/[^\s]+/g, '')
      text = text.replace(/[\w.+-]+@[\w-]+\.[\w.-]+/g, '')

      // 清除引用标记、任务列表等
      text = text.replace(/\[[0-9xX\s]+\]/g, '')
      text = text.replace(/\[.*?\]/g, '') // 清理任何剩余的方括号

      // 清除前端模板语法
      text = text.replace(/\{\{.*?\}\}/g, '')
      text = text.replace(/\{%.*?%\}/g, '')
      text = text.replace(/\{\#.*?\#\}/g, '')

      // 清理多余空白和格式
      text = text.replace(/\n\s*\n\s*\n/g, '\n\n') // 替换多个空行为两个空行
      text = text.replace(/\s{2,}/g, ' ') // 替换多个空格为单个空格
      text = text.replace(/^\s+|\s+$/gm, '') // 清除行首行尾空格

      // 清除残留的特殊字符
      text = text.replace(/[\\\/\*_~=+^<>\[\](){}`#]/g, ' ')
      text = text.replace(/&[a-zA-Z0-9]+;/g, ' ') // HTML实体

      // 清除特殊字符和控制字符
      text = text.replace(/[\u0000-\u001F\u007F-\u009F]/g, '')

      // 清除奇怪的Unicode字符，保留基本文字和标点
      text = text.replace(/[^\p{L}\p{N}\p{P}\p{Z}\p{Emoji}]/gu, ' ')

      // 再次整理多余的空格
      text = text.replace(/\s{2,}/g, ' ')

      // 用DOMPurify清理任何残留的HTML内容
      try {
        text = DOMPurify.sanitize(text, { ALLOWED_TAGS: [] })
      } catch (e) {
        console.error('DOMPurify sanitization failed:', e)
      }

      return text.trim()
    },

    /**
 * 美化搜索结果文本
 */
    beautifyResultText(text) {
      if (!text) return ''

      // 清除多余空白和换行符
      text = text.replace(/\s+/g, ' ')

      // 确保句子之间有适当的空格
      text = text.replace(/([.!?])\s*([A-Z])/g, '$1 $2')

      // 修复常见标点符号问题
      text = text.replace(/\s+([,.!?;:])/g, '$1')

      // 确保标点符号后有空格
      text = text.replace(/([,.!?;:])([^\s])/g, '$1 $2')

      // 清除可能残留的特殊字符和Markdown符号
      text = text.replace(/[\\*_~#<>[\](){}=`^]/g, '')

      // 处理重复的标点符号
      text = text.replace(/([.!?])[.!?]+/g, '$1')
      text = text.replace(/,+/g, ',')
      text = text.replace(/-+/g, '-')

      // 清除孤立的非文本字符
      text = text.replace(/\s[^\w\s,.!?;:]\s/g, ' ')

      // 处理连续的标点符号和空格
      text = text.replace(/\s+[,.!?;:]+\s+/g, '. ')

      // 清除结尾的标点符号（保留句号、感叹号和问号）
      text = text.trim().replace(/[,;:]$/, '')

      // 确保文本以标准的句点符号结尾（如果没有其他结束符号）
      if (!text.match(/[.!?]$/)) {
        text = text.replace(/[,;:]$/, '') + '.'
      }

      // 最终整理空格
      text = text.replace(/\s{2,}/g, ' ').trim()

      return text
    },

    /**
     * 处理搜索
     */
    async handleSearch() {
      // 隐藏搜索建议
      this.showSuggestions = false;

      const trimmedKeyword = this.params.keyword.trim();
      if (!trimmedKeyword) {
        this.searchResults = [];
        this.hasSearched = false;
        return;
      }

      this.loading = true;

      try {
        let res;

        // 优先使用标准搜索API，如果没有结果再尝试使用模糊搜索
        // 使用标准搜索API
        res = await searchArticlesApi({
          keyword: trimmedKeyword,
          pageNum: this.params.pageNum,
          pageSize: this.params.pageSize
        });

        // 如果标准搜索没有结果且模糊搜索功能已启用，则尝试模糊搜索
        if (this.useFuzzySearch && (!res.data || !res.data.records || res.data.records.length === 0)) {
          console.log('标准搜索无结果，尝试使用模糊搜索');
          res = await fuzzySearchArticlesApi(
            trimmedKeyword,
            this.fuzzySearchDistance,
            this.params.pageNum,
            this.params.pageSize
          );
        }

        if (Array.isArray(res.data)) {
          // 如果是数组格式的结果（模糊搜索返回格式）
          this.total = res.data.length;
          this.searchResults = this.processSearchResults(res.data);
        } else if (res.data && res.data.records) {
          // 标准搜索返回分页结果结构
          this.total = res.data.total;
          this.searchResults = this.processSearchResults(res.data.records);
        } else {
          // 如果没有数据或格式不符合预期
          this.total = 0;
          this.searchResults = [];
        }

        this.hasSearched = true;

        // 添加到搜索历史
        this.addToSearchHistory(trimmedKeyword);
      } catch (error) {
        console.error('搜索错误:', error);
        this.$message.error(error.message || '搜索失败，请稍后再试');
      } finally {
        this.loading = false;
      }
    },

    /**
     * 处理搜索结果
     */
    processSearchResults(results) {
      if (!results || results.length === 0) {
        return [];
      }

      return results.map(item => {
        // 彻底清除标题中的Markdown和HTML
        let plainTitle = '';
        if (item.title) {
          plainTitle = this.markdownToPlainText(item.title);
        }

        // 处理摘要，如果没有摘要则使用内容
        let plainSummary = '';
        if (item.summary) {
          plainSummary = this.markdownToPlainText(item.summary);
        } else if (item.contentMd) {
          plainSummary = this.markdownToPlainText(item.contentMd);
          // 限制摘要长度
          plainSummary = this.truncateText(plainSummary, 150);
        }

        // 确保移除所有可能的HTML实体和残留格式
        plainTitle = plainTitle.replace(/&[a-z0-9#]+;/gi, ' ');
        plainSummary = plainSummary.replace(/&[a-z0-9#]+;/gi, ' ');

        // 再次确保移除所有可能的Markdown格式残留物
        const cleanPattern = /[*_~=+`#<>[\](){}^]/g;
        plainTitle = plainTitle.replace(cleanPattern, '');
        plainSummary = plainSummary.replace(cleanPattern, '');

        // 美化文本显示
        plainTitle = this.beautifyResultText(plainTitle);
        plainSummary = this.beautifyResultText(plainSummary);

        return {
          ...item,
          title: plainTitle || this.truncateText(item.title, 50),
          summary: plainSummary
        };
      });
    },

    /**
     * 截断文本
     */
    truncateText(text, maxLength) {
      if (!text) return ''

      // 确保在截断前已经是纯文本
      const plainText = this.markdownToPlainText(text)

      return plainText.length > maxLength
        ? plainText.substring(0, maxLength) + '...'
        : plainText
    },
    /**
     * 高亮关键词
     */
    highlightKeyword(text) {
      if (!this.params.keyword || !text) return text;

      // 确保文本不含Markdown语法
      const plainText = this.markdownToPlainText(text);

      // 处理空字符串
      if (!plainText) return '';

      // 分割关键词，处理多个关键词搜索
      const keywords = this.params.keyword.trim().split(/\s+/).filter(k => k);
      if (keywords.length === 0) return plainText;

      let highlightedText = plainText;

      // 对每个关键词进行高亮处理
      keywords.forEach(keyword => {
        if (!keyword) return;
        // 使用转义后的关键词创建正则表达式，确保特殊字符被正确处理
        const regex = new RegExp(`(${this.escapeRegExp(keyword)})`, 'gi');
        highlightedText = highlightedText.replace(regex, '<mark>$1</mark>');
      });

      return highlightedText;
    },
    /**
     * 转义正则表达式
     */
    escapeRegExp(string) {
      return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
    },
    /**
     * 处理搜索结果点击
     */
    handleResultClick(item) {
      this.$router.push(`/post/${item.id}`)
      this.close()
    },

    /**
     * 关闭搜索对话框
     */
    close() {
      this.$store.commit('SET_SEARCH_VISIBLE', false)
      this.params.keyword = ''
      this.searchResults = []
      this.hasSearched = false
    },
    /**
     * 处理搜索对话框关闭
     */
    handleClose() {
      this.close()
    },
    /**
     * 处理键盘事件
     */
    handleKeydown(e) {
      if (e.key === 'Escape') {
        this.close()
      } else if (e.key === 'Enter') {
        // 如果按下回车，且正在加载建议，取消建议加载并立即执行搜索
        if (this.loadingSuggestions) {
          if (this.suggestionsTimeout) {
            clearTimeout(this.suggestionsTimeout);
            this.loadingSuggestions = false;
          }
        }
        // 隐藏建议，执行搜索
        this.showSuggestions = false;
        this.handleSearch();
      }
    },
    /**
     * 清除搜索
     */
    clearSearch() {
      this.params.keyword = '';
      this.searchResults = [];
      this.hasSearched = false;
      this.showSuggestions = false;
      this.$nextTick(() => {
        if (this.$refs.searchInput) {
          this.$refs.searchInput.focus();
        }
      });
    },
    /**
     * 格式化日期
     */
    formatDate(date) {
      return new Date(date).toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: 'long',
        day: 'numeric'
      })
    },
    /**
     * 处理文档点击事件，关闭建议框
     */
    handleDocumentClick(event) {
      // 检查点击是否在建议框或搜索输入框内
      const searchInput = this.$refs.searchInput;
      const suggestionBox = document.querySelector('.search-suggestions');

      if (searchInput && !searchInput.contains(event.target) &&
        suggestionBox && !suggestionBox.contains(event.target)) {
        this.showSuggestions = false;
      }
    },
  },

  mounted() {
    document.addEventListener('keydown', this.handleKeydown)
    // 添加全局点击事件监听器，关闭建议框
    document.addEventListener('click', this.handleDocumentClick)
  },

  beforeDestroy() {
    if (this.searchTimeout) {
      clearTimeout(this.searchTimeout)
    }
    if (this.suggestionsTimeout) {
      clearTimeout(this.suggestionsTimeout)
    }
    document.removeEventListener('keydown', this.handleKeydown)
    // 移除全局点击事件监听器
    document.removeEventListener('click', this.handleDocumentClick)
  }
}
</script>

<style lang="scss" scoped>
// CSS变量，支持明亮和暗黑模式
:root {
  --search-bg-color: #fff;
  --search-text-color: #333;
  --search-border-color: #dcdfe6;
  --search-placeholder: #909399;
  --tag-shadow: rgba(0, 0, 0, 0.1);
  --result-hover-shadow: rgba(0, 0, 0, 0.1);
}

.dark-mode {
  --search-bg-color: #1f1f1f;
  --search-text-color: #e0e0e0;
  --search-border-color: #3a3a3a;
  --search-placeholder: #909399;
  --tag-shadow: rgba(255, 255, 255, 0.05);
  --result-hover-shadow: rgba(255, 255, 255, 0.05);
}

// 对话框样式优化
.search-dialog {
  border-radius: 12px;
  overflow: hidden;

  :deep(.el-dialog__header) {
    padding: 15px 20px;
    border-bottom: 1px solid var(--search-border-color);

    .el-dialog__title {
      font-size: 18px;
      font-weight: 600;
    }
  }

  :deep(.el-dialog__body) {
    padding: 20px;
    position: relative;
  }
}

// 搜索输入框样式优化
.search-input-wrapper {
  display: flex;
  align-items: center;
  width: 100%;
  border: 2px solid var(--search-border-color);
  border-radius: 12px;
  padding: 12px 15px;
  margin-bottom: 20px;
  position: relative;
  transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
  background-color: var(--search-bg-color);
  z-index: 101; // 确保输入框在建议上方

  &:focus-within {
    border-color: var(--primary-color);
    box-shadow: 0 0 0 4px rgba(202, 90, 210, 0.15);
    transform: translateY(-1px);
  }

  .search-icon {
    color: var(--search-placeholder);
    font-size: 18px;
    margin-right: 12px;
    transition: color 0.3s ease;
  }

  &:focus-within .search-icon {
    color: var(--primary-color);
  }

  .clear-btn {
    cursor: pointer;
    padding: 6px;
    border-radius: 50%;
    color: var(--search-placeholder);
    transition: all 0.3s ease;
    display: flex;
    align-items: center;
    justify-content: center;

    &:hover {
      color: #f56c6c;
      background-color: rgba(245, 108, 108, 0.1);
    }
  }

  &.loading::after {
    content: '';
    position: absolute;
    right: 15px;
    width: 20px;
    height: 20px;
    border: 2px solid var(--search-border-color);
    border-top-color: var(--primary-color);
    border-radius: 50%;
    animation: spin 0.8s linear infinite;
  }

  .enter-tip {
    position: absolute;
    right: 15px;
    color: var(--search-placeholder);
    font-size: 13px;
    display: flex;
    align-items: center;
    opacity: 0.7;
    pointer-events: none;
    transition: opacity 0.3s ease, transform 0.3s ease;

    i {
      font-size: 14px;
      margin-right: 6px;
    }
  }

  .clear-btn+.enter-tip {
    right: 40px;
  }

  &.loading .enter-tip {
    display: none;
  }

  &:focus-within .enter-tip {
    opacity: 0;
    transform: translateX(10px);
  }
}

.search-input {
  flex: 1;
  border: none;
  outline: none;
  font-size: 16px;
  padding: 5px;
  width: 100%;
  background: transparent;
  color: var(--search-text-color);

  &::placeholder {
    color: var(--search-placeholder);
    opacity: 0.7;
  }
}

// 搜索历史记录样式
.search-history-section {
  margin-bottom: 30px;

  .history-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;

    h4 {
      margin: 0;
      color: var(--search-text-color);
      font-size: 16px;
      display: flex;
      align-items: center;
      position: relative;
      padding-left: 10px;

      &::before {
        content: '';
        position: absolute;
        left: 0;
        height: 18px;
        width: 3px;
        background: var(--primary-color);
        border-radius: 3px;
      }

      i {
        color: var(--primary-color);
        margin-right: 10px;
        font-size: 18px;
      }
    }

    .clear-history-btn {
      background: none;
      border: none;
      font-size: 13px;
      color: var(--search-placeholder);
      cursor: pointer;
      padding: 5px 10px;
      border-radius: 4px;
      display: flex;
      align-items: center;
      transition: all 0.3s ease;

      i {
        margin-right: 5px;
        font-size: 12px;
      }

      &:hover {
        color: #f56c6c;
        background-color: rgba(245, 108, 108, 0.1);
      }
    }
  }

  .history-list {
    display: flex;
    flex-direction: column;
    gap: 8px;

    .history-item {
      display: flex;
      align-items: center;
      padding: 8px 12px;
      border-radius: 6px;
      background-color: var(--search-bg-color);
      border: 1px solid var(--search-border-color);
      cursor: pointer;
      transition: all 0.3s ease;

      &:hover {
        border-color: var(--primary-color);
        box-shadow: 0 2px 8px var(--tag-shadow);
        transform: translateY(-1px);
      }

      .history-icon {
        color: var(--search-placeholder);
        margin-right: 10px;
        font-size: 14px;
        opacity: 0.7;
      }

      .history-keyword {
        flex: 1;
        color: var(--search-text-color);
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }

      .history-delete {
        width: 24px;
        height: 24px;
        display: flex;
        align-items: center;
        justify-content: center;
        color: var(--search-placeholder);
        border-radius: 50%;
        margin-left: 10px;
        opacity: 0;
        transition: all 0.2s ease;

        &:hover {
          background-color: rgba(245, 108, 108, 0.1);
          color: #f56c6c;
        }
      }

      &:hover .history-delete {
        opacity: 1;
      }
    }

    .history-expand {
      padding: 8px 0;
      text-align: center;
      color: var(--primary-color);
      font-size: 14px;
      cursor: pointer;
      transition: all 0.3s ease;

      &:hover {
        opacity: 0.8;
        transform: translateY(-1px);
      }

      i {
        margin-right: 5px;
      }
    }
  }
}

// 热门搜索关键词区域样式
.hot-keywords-section {
  margin-bottom: 30px;

  .hot-keywords-expand {
    padding: 8px 0;
    text-align: center;
    color: var(--primary-color);
    font-size: 14px;
    cursor: pointer;
    transition: all 0.3s ease;
    margin-top: 10px;
    border-top: 1px dashed var(--search-border-color);
    padding-top: 12px;

    &:hover {
      opacity: 0.8;
      transform: translateY(-1px);
    }

    i {
      margin-right: 5px;
      transition: transform 0.3s ease;
    }
  }

  .hot-keywords-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;

    h4 {
      margin: 0;
      color: var(--search-text-color);
      font-size: 16px;
      display: flex;
      align-items: center;
      position: relative;
      padding-left: 10px;

      &::before {
        content: '';
        position: absolute;
        left: 0;
        height: 18px;
        width: 3px;
        background: var(--primary-color);
        border-radius: 3px;
      }

      i {
        color: #ff6b6b;
        margin-right: 10px;
        font-size: 18px;
      }
    }
  }

  .hot-keywords-list {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 10px;

    .hot-keyword-item {
      display: flex;
      align-items: center;
      padding: 10px 15px;
      border-radius: 8px;
      background-color: var(--search-bg-color);
      border: 1px solid var(--search-border-color);
      cursor: pointer;
      transition: all 0.3s ease;
      position: relative;
      overflow: hidden;

      &::before {
        content: '';
        position: absolute;
        left: -100%;
        top: 0;
        width: 100%;
        height: 100%;
        background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.1), transparent);
        transition: all 0.5s ease;
      }

      &:hover {
        border-color: #ff6b6b;
        box-shadow: 0 4px 12px rgba(255, 107, 107, 0.2);
        transform: translateY(-3px);

        &::before {
          left: 100%;
        }
      }

      .hot-keyword-rank {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 24px;
        height: 24px;
        border-radius: 50%;
        background-color: var(--search-border-color);
        color: var(--search-text-color);
        font-size: 12px;
        font-weight: bold;
        margin-right: 12px;
        transition: all 0.3s ease;
        box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);

        &.top-rank {
          background-color: #ff6b6b;
          color: white;
          box-shadow: 0 2px 8px rgba(255, 107, 107, 0.3);
        }

        &.normal-rank {
          background-color: #7a7a7a;
          color: white;
          opacity: 0.7;
        }
      }

      .hot-keyword-text {
        flex: 1;
        color: var(--search-text-color);
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        font-size: 14px;
      }
    }
  }
}

// 搜索结果列表样式
.search-results {
  max-height: 60vh;
  overflow-y: auto;
  padding-right: 10px;
  margin-top: 20px;
  scrollbar-width: thin;

  &::-webkit-scrollbar {
    width: 6px;
  }

  &::-webkit-scrollbar-track {
    background: transparent;
  }

  &::-webkit-scrollbar-thumb {
    background-color: var(--search-border-color);
    border-radius: 3px;

    &:hover {
      background-color: var(--primary-color);
    }
  }
}

.search-result-item {
  padding: 20px;
  cursor: pointer;
  border-radius: 12px;
  margin-bottom: 16px;
  transition: all 0.4s cubic-bezier(0.25, 0.8, 0.25, 1);
  border: 1px solid var(--search-border-color);
  background-color: var(--search-bg-color);
  position: relative;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

  &::before {
    content: '';
    position: absolute;
    left: 0;
    top: 0;
    width: 4px;
    height: 100%;
    background: linear-gradient(to bottom, var(--primary-color), rgba(202, 90, 210, 0.2));
    opacity: 0;
    transition: opacity 0.3s ease;
  }

  &::after {
    content: '';
    position: absolute;
    top: 0;
    left: -100%;
    width: 100%;
    height: 100%;
    background: linear-gradient(90deg,
        transparent,
        rgba(255, 255, 255, 0.1),
        transparent);
    transition: left 0.7s ease;
  }

  &:hover {
    transform: translateY(-4px) scale(1.01);
    box-shadow: 0 8px 20px var(--result-hover-shadow);
    border-color: var(--primary-color);
    padding-left: 26px;

    &::before {
      opacity: 1;
    }

    &::after {
      left: 100%;
    }
  }

  .result-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 14px;
    position: relative;

    h3 {
      margin: 0;
      font-size: 18px;
      color: var(--primary-color);
      flex: 1;
      transition: color 0.3s ease;
      font-weight: 600;
      line-height: 1.4;
      position: relative;
      display: inline-block;

      &::after {
        content: '';
        position: absolute;
        bottom: -4px;
        left: 0;
        width: 0;
        height: 2px;
        background: linear-gradient(90deg, var(--primary-color), transparent);
        transition: width 0.4s ease;
      }
    }

    .search-result-item:hover h3::after {
      width: 100%;
    }

    .result-date {
      font-size: 12px;
      color: var(--search-placeholder);
      margin-left: 14px;
      padding: 4px 10px;
      background-color: rgba(202, 90, 210, 0.1);
      border-radius: 20px;
      font-weight: 500;
      white-space: nowrap;
      box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
      transition: all 0.3s ease;

      .search-result-item:hover & {
        background-color: rgba(202, 90, 210, 0.2);
        transform: translateY(-1px);
      }
    }
  }

  .result-summary {
    margin: 0 0 15px;
    font-size: 14px;
    color: var(--search-text-color);
    line-height: 1.8;
    opacity: 0.9;
    white-space: pre-line;
    word-break: break-word;
    text-align: justify;
    position: relative;
    padding-left: 2px;
    max-height: 5.4em; // 显示3行
    overflow: hidden;
    display: -webkit-box;
    -webkit-line-clamp: 3;
    -webkit-box-orient: vertical;

    &::after {
      content: '...';
      position: absolute;
      right: 0;
      bottom: 0;
      padding: 0 3px;
      background-color: var(--search-bg-color);
    }

    // 段落间距优化
    p {
      margin: 8px 0;
    }

    // 关键词高亮增强
    mark {
      background-color: rgba(202, 90, 210, 0.2);
      padding: 2px 4px;
      border-radius: 3px;
      font-weight: 600;
      color: var(--primary-color);
      transition: all 0.2s ease;
      box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);

      &:hover {
        background-color: rgba(202, 90, 210, 0.4);
      }
    }
  }

  .result-footer {
    display: flex;
    gap: 18px;
    font-size: 13px;
    color: var(--search-placeholder);
    padding-top: 8px;
    border-top: 1px dashed rgba(125, 125, 125, 0.1);

    i {
      margin-right: 6px;
      transition: transform 0.3s ease;
    }

    .result-category,
    .result-views {
      display: flex;
      align-items: center;
      padding: 4px 0;
      transition: all 0.3s ease;

      &:hover {
        color: var(--primary-color);

        i {
          transform: scale(1.2);
        }
      }
    }
  }
}

// 标签样式，添加渐变和流光效果
.hot-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  margin-top: 15px;
}

.hot-tag {
  padding: 10px 18px;
  border-radius: 20px;
  font-size: 14px;
  font-weight: 500;
  color: #333;
  cursor: pointer;
  text-decoration: none;
  position: relative;
  overflow: hidden;
  transition: all 0.4s cubic-bezier(0.25, 0.8, 0.25, 1);
  box-shadow: 0 3px 10px var(--tag-shadow);
  text-shadow: 0 1px 1px rgba(0, 0, 0, 0.1);
  background-size: 200% auto;
  background-position: 0 100%;
  animation: gradientShift 3s ease infinite alternate;

  // 流光效果
  &::after {
    content: '';
    position: absolute;
    top: -50%;
    left: -100%;
    width: 80%;
    height: 200%;
    background: rgba(255, 255, 255, 0.2);
    transform: rotate(30deg);
    transition: transform 0.6s ease;
  }

  &:hover {
    transform: translateY(-5px) scale(1.05);
    box-shadow: 0 7px 20px var(--tag-shadow);
    background-position: 100% 0;
    transition: all 0.4s ease;

    &::after {
      transform: translateX(300%) rotate(30deg);
    }
  }
}

@keyframes gradientShift {
  0% {
    background-position: 0% 50%;
  }

  50% {
    background-position: 100% 50%;
  }

  100% {
    background-position: 0% 50%;
  }
}

// 标签颜色
.tag-color-0 {
  background: linear-gradient(135deg, #ff9a9e 0%, #fad0c4 100%);
}

.tag-color-1 {
  background: linear-gradient(135deg, #a1c4fd 0%, #c2e9fb 100%);
}

.tag-color-2 {
  background: linear-gradient(135deg, #fbc2eb 0%, #a6c1ee 100%);
}

.tag-color-3 {
  background: linear-gradient(135deg, #84fab0 0%, #8fd3f4 100%);
}

.tag-color-4 {
  background: linear-gradient(135deg, #fccb90 0%, #d57eeb 100%);
}

.tag-color-5 {
  background: linear-gradient(135deg, #e0c3fc 0%, #8ec5fc 100%);
}

.tag-color-6 {
  background: linear-gradient(135deg, #f6d365 0%, #fda085 100%);
}

.tag-color-7 {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.tag-color-8 {
  background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
}

// 高亮关键词增强样式
:deep(mark) {
  background-color: rgba(202, 90, 210, 0.2);
  padding: 2px 4px;
  border-radius: 3px;
  font-weight: 600;
  color: var(--primary-color);
  transition: all 0.3s ease;
  box-decoration-break: clone;
  -webkit-box-decoration-break: clone;

  &:hover {
    background-color: rgba(202, 90, 210, 0.4);
  }
}

// 分页器样式优化
.pagination-box {
  margin-top: 20px;
  display: flex;
  justify-content: center;

  :deep(.el-pagination) {
    padding: 0;

    button,
    .el-pager li {
      background-color: var(--search-bg-color);
      color: var(--search-text-color);

      &:hover,
      &.active {
        color: var(--primary-color);
      }
    }
  }
}

// 动画
@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

// 空状态样式优化
:deep(.el-empty) {
  padding: 20px 0;

  .el-empty__description {
    color: var(--search-placeholder);
  }

  .el-empty__image {
    opacity: 0.7;
  }
}

// 搜索建议样式
.search-suggestions {
  position: absolute;
  width: calc(100% - 40px);
  max-height: 200px;
  overflow-y: auto;
  background: var(--search-bg-color, #fff);
  border: 1px solid var(--search-border-color);
  border-radius: 8px;
  z-index: 100;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
  margin-top: 2px;
  padding: 6px 0;
  backdrop-filter: blur(10px);
  animation: fadeInDown 0.3s ease-out;

  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: var(--search-bg-color, #fff);
    opacity: 0.98;
    z-index: -1;
    border-radius: 8px;
  }

  .suggestion-item {
    padding: 10px 15px;
    cursor: pointer;
    display: flex;
    align-items: center;
    transition: all 0.3s ease;
    position: relative;
    border-left: 3px solid transparent;

    i {
      color: var(--primary-color, #ca5ad2);
      margin-right: 10px;
      opacity: 0.8;
      transition: all 0.3s ease;
    }

    &:hover {
      background-color: rgba(202, 90, 210, 0.1);
      border-left-color: var(--primary-color, #ca5ad2);
      padding-left: 20px;

      i {
        transform: scale(1.2);
        opacity: 1;
      }
    }

    &:not(:last-child)::after {
      content: '';
      position: absolute;
      left: 15px;
      right: 15px;
      bottom: 0;
      height: 1px;
      background-color: var(--search-border-color, #eee);
      opacity: 0.5;
    }

    mark {
      background-color: rgba(202, 90, 210, 0.2);
      padding: 2px 4px;
      border-radius: 3px;
      font-weight: 600;
      color: var(--primary-color, #ca5ad2);
      transition: background-color 0.3s ease;

      &:hover {
        background-color: rgba(202, 90, 210, 0.4);
      }
    }
  }

  &::-webkit-scrollbar {
    width: 6px;
  }

  &::-webkit-scrollbar-track {
    background: transparent;
  }

  &::-webkit-scrollbar-thumb {
    background-color: var(--search-border-color);
    border-radius: 3px;

    &:hover {
      background-color: var(--primary-color, #ca5ad2);
    }
  }
}

@keyframes fadeInDown {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

// 搜索选项样式
.search-options {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  /* 让按钮靠右对齐 */
  margin: 15px 0;
  padding: 12px 15px;
  background-color: var(--search-bg-color, #fff);
  border-radius: 8px;
  border: 1px solid var(--search-border-color);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  position: relative;

  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: var(--search-bg-color, #fff);
    opacity: 0.98;
    z-index: -1;
    border-radius: 8px;
  }

  // 移除模糊搜索相关样式

  :deep(.el-switch__label) {
    color: var(--search-text-color, #333);
  }

  .search-button {
    background-color: var(--primary-color, #ca5ad2);
    border-color: var(--primary-color, #ca5ad2);
    transition: all 0.3s ease;
    padding: 10px 20px;
    font-size: 14px;
    font-weight: 500;
    letter-spacing: 0.5px;

    &:hover,
    &:focus {
      background-color: darken(#ca5ad2, 10%);
      border-color: darken(#ca5ad2, 10%);
      transform: translateY(-1px) scale(1.03);
      box-shadow: 0 4px 12px rgba(202, 90, 210, 0.4);
    }

    i {
      margin-right: 6px;
      font-size: 15px;
    }
  }
}

// 暗黑模式适配
.dark-mode {
  .search-suggestions {
    background-color: rgba(31, 31, 31, 0.95);
    border-color: #3a3a3a;
    box-shadow: 0 4px 15px rgba(0, 0, 0, 0.4);

    &::before {
      background-color: #1f1f1f;
      opacity: 0.95;
    }

    .suggestion-item {
      &:hover {
        background-color: rgba(202, 90, 210, 0.15);
      }

      &:not(:last-child)::after {
        background-color: #3a3a3a;
      }

      mark {
        background-color: rgba(202, 90, 210, 0.25);
        color: #e0e0e0;

        &:hover {
          background-color: rgba(202, 90, 210, 0.4);
        }
      }
    }
  }

  .search-options {
    background-color: #1f1f1f;
    border-color: #3a3a3a;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);

    &::before {
      background-color: #1f1f1f;
      opacity: 0.98;
    }

    .distance-label {
      color: #e0e0e0;
    }

    :deep(.el-switch__label) {
      color: #e0e0e0;
    }
  }

  .hot-tag {
    color: #f0f0f0;
    text-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);
    opacity: 0.85;
    box-shadow: 0 3px 10px rgba(0, 0, 0, 0.3);

    &:hover {
      opacity: 1;
      box-shadow: 0 7px 20px rgba(0, 0, 0, 0.4);
    }
  }

  .search-result-item {
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);

    &::after {
      background: linear-gradient(90deg,
          transparent,
          rgba(255, 255, 255, 0.05),
          transparent);
    }

    &:hover {
      box-shadow: 0 8px 20px rgba(0, 0, 0, 0.3);
    }

    .result-summary::after {
      background-color: var(--search-bg-color);
    }

    .result-footer {
      border-top: 1px dashed rgba(255, 255, 255, 0.1);
    }
  }

  // 热门搜索在暗黑模式下的样式
  .hot-keywords-section {
    .hot-keyword-item {
      border-color: #3a3a3a;
      background-color: rgba(255, 255, 255, 0.03);
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);

      &:hover {
        background-color: rgba(255, 255, 255, 0.05);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
      }

      .normal-rank {
        background-color: #555;
      }
    }

    .hot-keywords-expand {
      border-top: 1px dashed rgba(255, 255, 255, 0.1);
    }
  }

  // 搜索历史在暗黑模式下的样式
  .search-history-section {
    .history-item {
      border-color: #3a3a3a;
      background-color: rgba(255, 255, 255, 0.03);
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);

      &:hover {
        background-color: rgba(255, 255, 255, 0.05);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
      }

      .history-keyword {
        color: #e0e0e0;
      }

      .history-icon {
        color: #999;
      }
    }

    .clear-history-btn:hover {
      background-color: rgba(245, 108, 108, 0.15);
    }

    .history-expand {
      border-top: 1px dashed rgba(255, 255, 255, 0.1);
    }
  }

  // 搜索选项和按钮在暗黑模式下的样式
  .search-options {
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);

    .search-button {
      &:hover {
        box-shadow: 0 4px 12px rgba(202, 90, 210, 0.5);
      }
    }
  }
}
</style>